﻿using Dapper;
using Microsoft.AspNetCore.Http;
using PersonalWebsite.Core.CQRS;
using PersonalWebsite.Core.Helpers;
using PersonalWebsite.Core.Result;
using System.Net.Http.Headers;

namespace PersonalWebsite.Application.Queries.Website;

public record GetShowVO
{
    public int Id { get; init; }
    public string Name { get; init; }
    public string Top { get; init; }
    public int Year { get; init; }
    public string Score { get; init; }
    public string Cover { get; private set; }
    public string Link { get; init; }

    public void SetInternetImageUrl(IHttpContextAccessor httpContextAccessor)
    {
        if (!string.IsNullOrEmpty(Cover))
        {
            Cover = FileHelper.GetShowFile(httpContextAccessor, Cover);
        }
    }
}

public record GetShowVOQuery : IQuery<ApiResult<List<GetShowVO>>, List<GetShowVO>>
{

}

internal class GetShowVOQueryHandler : QueryHandler<GetShowVOQuery, ApiResult<List<GetShowVO>>, List<GetShowVO>>
{
    private readonly IHttpContextAccessor httpContextAccessor;
    private readonly IDBConnectionFactory dBConnectionFactory;

    public GetShowVOQueryHandler(IHttpContextAccessor httpContextAccessor, IDBConnectionFactory dBConnectionFactory) : base(dBConnectionFactory)
    {
        this.httpContextAccessor = httpContextAccessor;
        this.dBConnectionFactory = dBConnectionFactory;
    }

    public override async Task<ApiResult<List<GetShowVO>>> Handle(GetShowVOQuery request, CancellationToken cancellationToken)
    {

        using var dbConnection = dBConnectionFactory.GetDbConnection();
        string sql = "SELECT * FROM WS_Show";
        var data = await dbConnection.QueryAsync<GetShowVO>(sql);

        var result = new List<GetShowVO>();
        if (data != null && data.Any())
        {
            foreach (var item in data)
            {
                item.SetInternetImageUrl(httpContextAccessor);
                result.Add(item);
            }
        }

        return await Task.FromResult(ApiResult<List<GetShowVO>>.Success(result));
    }
}